package com.ecloud.gardenscenter.service.mqtt;

import com.alibaba.fastjson.JSON;
import com.ecloud.gardenscenter.common.exception.InnerException;
import com.ecloud.gardenscenter.domain.SwitchOrder;
import com.ecloud.gardenscenter.mqtt.MqttTemplate;
import com.ecloud.gardenscenter.service.MqttService;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Squbi
 */
@Service
public class MqttServiceImpl implements MqttService {
    @Autowired
    private MqttTemplate template;

    public void publish(String topic, byte[] payload) {
        try {
            MqttMessage message = new MqttMessage(payload);
            message.setQos(2);
            template.publish(topic, message);
        } catch (MqttException e) {
            throw new InnerException("mqtt publish exception : " + e);
        }
    }

    @Override
    public void sendSwitch(String topic, int deviceId, int operation) {
        SwitchOrder switchOrder = new SwitchOrder();
        switchOrder.setOperation(operation);
        switchOrder.setId(deviceId);
        publish(topic, JSON.toJSONString(switchOrder).getBytes());
    }
}
